//
//  SetViewController.m
//  FreeTrip
//
//  Created by 邓芮 on 15/11/27.
//  Copyright © 2015年 邓芮. All rights reserved.
//

#import "SetViewController.h"
#import "SetButton.h"
@interface SetViewController ()

@end

@implementation SetViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.navigationItem.title = @"基本设置";
    self.view.backgroundColor = [UIColor whiteColor];
    NSArray *array = @[@"使用流量时通知我", @"当前版本信息", @"清除缓存"];
    for (int i = 0; i < array.count; i++)
    {
        CGFloat height = 60 * KScreenWidth / 320;
        CGFloat gapHeight = 30;
        CGFloat y = (KScreenHeight - 64 - height * array.count - gapHeight * (array.count - 1)) / 2;
        SetButton *set = [SetButton buttonWithType:UIButtonTypeSystem];
        set.frame = CGRectMake(0, y + (gapHeight + height) * i, KScreenWidth, height);
        set.title.text = [NSString stringWithFormat:@"-- %@ --", array[i]];
        set.title.font = [UIFont systemFontOfSize:20 * KScreenWidth / 414];
        if (i ==0)
        {
            if([[NSUserDefaults standardUserDefaults]boolForKey:StrUsertrafficToRemind])
            {
                set.stateLabel.text = @"关闭";
            }
            else
            {
                set.stateLabel.text = @"开启";
            }
            
        }
        else if(i==1)
        {
            set.userInteractionEnabled = NO;
            set.stateLabel.text = [NSString stringWithFormat:@"%ld.0版本",(long)[self getVersion]];
        }
        else if(i==2)
        {
            set.stateLabel.text = [NSString stringWithFormat:@"%.0fM",[self getSizeForCaches]];
        }
        set.tag = 1000 + i;
        [set addTarget:self action:@selector(setButton:) forControlEvents:UIControlEventTouchUpInside];
        [self.view addSubview:set];
    }



}

- (NSInteger )getVersion
{
    NSDictionary *infoDic = [[NSBundle mainBundle] infoDictionary];
    
    
    NSString *appVersion = [infoDic objectForKey:@"CFBundleVersion"];
    return [appVersion integerValue];
}

- (void)setButton:(SetButton *)btn
{
    NSInteger num = btn.tag;
    if (num == 1000)
    {
        if([btn.stateLabel.text isEqualToString:@"关闭"])
        {
            btn.stateLabel.text = @"开启";
            [[NSUserDefaults standardUserDefaults]setBool:NO forKey:StrUsertrafficToRemind];
        }
        else
        {
            btn.stateLabel.text = @"关闭";
            [[NSUserDefaults standardUserDefaults]setBool:YES forKey:StrUsertrafficToRemind];
            
        }
    }
        else if (num == 1002)
    {
        /**/
        //清除缓存的方法;
        [[SDImageCache sharedImageCache] clearDisk];
        NSString *newPath = [self newFilePath];
        NSFileManager *manager = [NSFileManager defaultManager];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
                       {
                           if([manager fileExistsAtPath:newPath])
                           {
                               [manager removeItemAtPath:newPath error:nil];
                           }
                           
                           dispatch_async(dispatch_get_main_queue(), ^
                                          {
                                              btn.stateLabel.text =  @"缓存已清";
                                              
                                              UIAlertController *alerview = [UIAlertController alertControllerWithTitle:nil message:@"缓存已清哦!!!" preferredStyle:UIAlertControllerStyleAlert];
                                              
                                              [self presentViewController:alerview animated:YES completion:^
                                               {
                                                   [self performSelector:@selector(alerViewAction:) withObject:alerview afterDelay:0.5];
                                               }];
                                              
                                          });
                       });
        
       // NSLog(@"缓存已清理!!!");
         
        /*
        NSString *newPath = [self newFilePath];
        NSFileManager *manager = [NSFileManager defaultManager];
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^
                       {
                           if([manager fileExistsAtPath:newPath])
                           {
                               [self removeAllFileWithFile:newPath];
                           }
                           
                           dispatch_async(dispatch_get_main_queue(), ^
                                          {
                                              btn.stateLabel.text =  @"0M";
                                              
                                              UIAlertController *alerview = [UIAlertController alertControllerWithTitle:nil message:@"缓存已清哦!!!" preferredStyle:UIAlertControllerStyleAlert];
                                              
                                              [self presentViewController:alerview animated:YES completion:^
                                               {
                                                   [self performSelector:@selector(alerViewAction:) withObject:alerview afterDelay:0.5];
                                               }];
                                              
                                          });
                       });


         */
    }
    
   }



- (void)alerViewAction:(UIAlertController *)aler
{
    [aler dismissViewControllerAnimated:YES completion:nil];
}

// 设置文件名
- (NSString *)newFilePath
{
    return [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject] stringByAppendingPathComponent:@"strategy"];
}

// 获取缓存大小
- (CGFloat)getSizeForCaches
{
    NSString *newPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES)firstObject];
    NSLog(@"%@",newPath);
  return   [self folderSizeAtPath:newPath];
   
}

- (long long) fileSizeAtPath:(NSString*) filePath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if ([manager fileExistsAtPath:filePath]){
        
        return [[manager attributesOfItemAtPath:filePath error:nil] fileSize];
        
    }
    
    return 0;
    
}

//遍历文件夹获得文件夹大小，返回多少M

- (float ) folderSizeAtPath:(NSString*) folderPath{
    
    NSFileManager* manager = [NSFileManager defaultManager];
    
   
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:folderPath] objectEnumerator];
    
    NSString* fileName;
    
    long long folderSize = 0;
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [folderPath stringByAppendingPathComponent:fileName];
        
        folderSize += [self fileSizeAtPath:fileAbsolutePath];
        
    }
    
    return folderSize/(1024.0*1024.0);
    
}

/*
- (void)removeAllFileWithFile:(NSString *)path
{
    NSFileManager* manager = [NSFileManager defaultManager];
    
    if (![manager fileExistsAtPath:path]) return ;
    
    NSEnumerator *childFilesEnumerator = [[manager subpathsAtPath:path] objectEnumerator];
    
    NSString* fileName;
    
    
    
    while ((fileName = [childFilesEnumerator nextObject]) != nil){
        
        NSString* fileAbsolutePath = [path stringByAppendingPathComponent:fileName];
       BOOL flag =  [manager removeItemAtPath:fileAbsolutePath error:nil];
        NSLog(@"%d",flag);
        
    }
    
   

}
*/
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
